/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/** 
 * ClassName: Demo2 <br/> 
 * Function: TODO 功能描述 <br/> 
 * date: 2017年10月30日 下午9:42:17 <br/> 
 * 
 * @author wd
 * @version  
 * @since JDK 1.8 
 */
public class Demo2 {
public static void main(String[] args) throws IOException {
		
		OkHttpClient client = new OkHttpClient();
		
		String url="http://www.ivsky.com/tupian/";
		
		Request request = new Request.Builder()
			      .url(url)
			      
			      .build();
		
		Response response = client.newCall(request).execute();
		String s=response.body().string();
//		System.out.println(s);
		
		
		boolean flag=true;
		int i=0;
		while(flag) {
			i++;
			String s1="";
			if(s.indexOf("<img")!=-1) {
				s1=s.substring(s.indexOf("<img src=\"")+10, s.length()-1);
				s1=s1.substring(0, s1.indexOf("\""));
				getPictrue(s1,i);
			}else {
				flag=false;
			}
			s=s.substring(s.indexOf("<img src=\"")+10);
			System.out.println(s1);
			
		}
		//jsoup解析html，取出HTMl中所有的Img标签，拿到标签上的 src地址，然后再使用 OKHttpClient将请求发出后保存到磁盘
		
	}
	public static String getPictrue(String s,int i){
OkHttpClient client = new OkHttpClient();
		File file=new File("D://学习/"+i+".jpg");
		String url=s;
		try {
			URL ul=new URL(url);
			InputStream is=ul.openStream();
			FileOutputStream fis=new FileOutputStream(file);
			BufferedInputStream bis=new BufferedInputStream(is);
			BufferedOutputStream bos=new BufferedOutputStream(fis);
			int a=-1;
			StringBuffer sb=null;
			byte[] b=new byte[1024];
			while((a=bis.read(b))!=-1) {
				if(a==1024) {
				bos.write(b);
				}else {
				bos.write(a);
				}
			}
			bos.flush();
			bis.close();
			bos.close();
			is.close();
			fis.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "good";
		
	}

}
